import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/data/user_cart.dart';
import 'package:labcloud_app/data/product.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/api/graphql/product_gql.dart';

class UserCartModel extends ChangeNotifier {
  List<UserCart> _cart = [];
  bool _isLoading = false;
  String _errorMessage = '';
  bool _isLoadCartCalled = false;

  List<UserCart> get cart => _cart;
  bool get hasCartItems => _cart.isNotEmpty;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  bool get isLoadCartCalled => _isLoadCartCalled;

  // 计算购物车总价
  double get totalPrice {
    return _cart.fold(0.0, (sum, cartItem) {
      if (cartItem.product != null && cartItem.quantity != null) {
        final price = double.tryParse(cartItem.product!.price ?? '0') ?? 0;
        return sum + (price * cartItem.quantity!.toDouble());
      }
      return sum;
    });
  }

  // 清空购物车
  void clearCart() {
    _cart.clear();
    notifyListeners();
  }

  // 重置加载状态
  void resetLoadStatus() {
    _isLoadCartCalled = false;
    _isLoading = false;
    _errorMessage = '';
  }
  
  // 加载购物车数据
  Future<void> loadCartItems(GraphQLClient client) async {
    // 防止重复调用
    if (_isLoadCartCalled) return;
    
    try {
      _isLoading = true;
      _errorMessage = '';
      _isLoadCartCalled = true;
      notifyListeners();

      final result = await client.query(
        QueryOptions(
          document: gql(UserGQL.fetchUserCartItems),
          fetchPolicy: FetchPolicy.networkOnly
        ),
      );

      if (result.hasException) {
        _errorMessage = '获取购物车失败: ${result.exception.toString()}';
        debugPrint('获取购物车失败: ${result.exception.toString()}');
        _isLoadCartCalled = false; // 出错时重置标志，允许重试
      } else {
        // 解析购物车数据
        final items = result.data!['user']['currentUser']['cartItems'] as List?;
        print("获取到购物车数据: $items");
        
        List<UserCartItems> cartItems = items != null
            ? items.map((item) => UserCartItems.fromJson(item)).toList()
            : [];
            
        List<UserCart> cartItemList = [];
        
        for (var item in cartItems) {
          final productResult = await client.query(
            QueryOptions(
              document: gql(ProductGQL.fetchProductDetail),
              variables: {
                'id': item.productId!,
              },
            ),
          );
          
          if (productResult.hasException) {
            debugPrint('获取商品详情失败: ${productResult.exception.toString()}');
            continue;
          }
          
          final product = Product.fromJson(productResult.data!['product']['productById']);

          cartItemList.add(UserCart(
            id: item.id,
            product: product,
            quantity: item.quantity,
            createTime: item.createTime,
            updateTime: item.updateTime,
            productId: item.productId,
            userId: item.userId,
          ));
        }
        clearCart();
        _cart = cartItemList;
        _errorMessage = '';
        notifyListeners();
      }
    } catch (e) {
      _errorMessage = '加载购物车异常: $e';
      debugPrint('加载购物车异常: $e');
      _isLoadCartCalled = false; // 出错时重置标志，允许重试
    } finally {
      _isLoading = false;
      Future.microtask(() => notifyListeners());
    }
  }

  // 添加商品到购物车
  Future<UserCart?> addToCart(GraphQLClient client, String productId, int quantity) async {
    try {
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchAddToCart),
          variables: {
            'productId': productId,
            'quantity': quantity,
          },
        ),

      );

      if (result.hasException) {
        _errorMessage = '添加商品到购物车失败: ${result.exception.toString()}';
        debugPrint('添加商品到购物车失败: ${result.exception.toString()}');
        Future.microtask(() => notifyListeners());
        return null;
      }



      // 检查返回数据是否有效
      final cartItemData = result.data?['user']['addCurrentUserCartItem'];
      if (cartItemData == null) {
        _errorMessage = '添加商品到购物车失败: 服务器返回空数据';
        debugPrint('添加商品到购物车失败: 服务器返回空数据');
        Future.microtask(() => notifyListeners());
        return null;
      }
      
      UserCartItems item = UserCartItems.fromJson(cartItemData);

      final productResult = await client.query(
        QueryOptions(
          document: gql(ProductGQL.fetchProductDetail),
          variables: {
            'id': productId,
          },
        ),
      );
      
      if (productResult.hasException) {
        _errorMessage = '获取商品详情失败: ${productResult.exception.toString()}';
        debugPrint('获取商品详情失败: ${productResult.exception.toString()}');
        Future.microtask(() => notifyListeners());
        return null;
      }
      
      final product = Product.fromJson(productResult.data!['product']['productById']);

      UserCart cartItem = UserCart(
        id: item.id,
        product: product,
        quantity: item.quantity,
        createTime: item.createTime,
        updateTime: item.updateTime,
        productId: item.productId,
        userId: item.userId,
      );
      
      // 检查购物车中是否已存在该商品
      final existingIndex = _cart.indexWhere((item) => item.productId == productId.toString());
      if (existingIndex != -1) {
        // 如果已存在，则更新数量
        _cart[existingIndex].quantity = (_cart[existingIndex].quantity ?? 0) + quantity;
      } else {
        // 否则添加新商品
        _cart.add(cartItem);
      }
      
      _errorMessage = '';
      notifyListeners();
      
      return cartItem;
    } catch (e) {
      _errorMessage = '添加商品到购物车异常: $e';
      debugPrint('添加商品到购物车异常: $e');
      notifyListeners();
      return null;
    }
  }

  // 从购物车删除商品
  Future<bool> removeFromCart(GraphQLClient client, String cartItemId) async {
    try {
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchRemoveFromCart),
          variables: {
            'cartItemId': cartItemId,
          },
        ),
      );

      if (result.hasException) {
        _errorMessage = '从购物车删除失败: ${result.exception.toString()}';
        debugPrint('从购物车删除失败: ${result.exception.toString()}');
        notifyListeners();
        return false;
      } else {
        // 检查服务器返回结果
        final deleteResult = result.data?['user']['deleteCurrentUserCartItem'];
        if (deleteResult == null || deleteResult != true) {
          _errorMessage = '从购物车删除失败: 服务器返回错误结果';
          debugPrint('从购物车删除失败: 服务器返回错误结果');
          notifyListeners();
          return false;
        }
        
        // 从本地购物车删除
        _cart.removeWhere((item) => item.id == cartItemId.toString());
        _errorMessage = '';
        notifyListeners();
        return true;
      }
    } catch (e) {
      _errorMessage = '从购物车删除异常: $e';
      debugPrint('从购物车删除异常: $e');
      notifyListeners();
      return false;
    }
  }

  // 更新购物车商品数量
  Future<bool> updateCartItemCount(GraphQLClient client, String cartItemId, int quantity) async {
    try {
      // 如果数量为0，则删除商品
      if (quantity <= 0) {
        return await removeFromCart(client, cartItemId);
      }
      
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchUpdateCartItem),
          variables: {
            'cartItemId': cartItemId.toString(),
            'quantity': quantity,
          },
        ),
      );

      if (result.hasException) {
        _errorMessage = '更新购物车失败: ${result.exception.toString()}';
        debugPrint('更新购物车失败: ${result.exception.toString()}');
        notifyListeners();
        return false;
      } else {
        // 更新本地购物车
        final index = _cart.indexWhere((item) => item.id == cartItemId.toString());
        if (index != -1) {
          _cart[index].quantity = quantity;
        }
        _errorMessage = '';
        notifyListeners();
        return true;
      }
    } catch (e) {
      _errorMessage = '更新购物车异常: $e';
      debugPrint('更新购物车异常: $e');
      notifyListeners();
      return false;
    }
  }
  
  // 重置购物车状态，用于清空购物车后重新加载
  void resetCartState() {
    _isLoadCartCalled = false;
    _cart.clear();
    _errorMessage = '';
    notifyListeners();
  }
}